﻿using ljh.ModbusRTULib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ljh.THProjectMain
{
    public partial class FrmMain : Form
    {
        /// <summary>
        /// ModbusRTU协议通信对象
        /// </summary>
        private ModbusRTU modbusRTU  = new ModbusRTU();
        /// <summary>
        /// 串口连接状态标志位
        /// </summary>
        /// <remarks>
        /// true连接设备，false断开连接
        /// </remarks>
        private bool _isConnected = false;

        /// <summary>
        /// 串口连接状态标志位
        /// </summary>
        /// <remarks>
        /// true连接设备，false断开连接
        /// 设置属性值时会根据属性值设置样式属性
        /// </remarks>
        public bool IsConnected
        {
            get { return _isConnected; }

            set
            {
                _isConnected = value;//保存当前的状态
                this.btnConnectAndDIsconnect.Text = value ? "断 开 连 接" : "连 接 设 备";
                if (value)  //如果打开连接
                {
                    this.btnConnectAndDIsconnect.BackColor = Color.Red;
                    this.btnConnectAndDIsconnect.ForeColor = Color.White;
                    this.lblConnectedStatus.ForeColor = Color.Green;
                }
                else
                {
                    this.btnConnectAndDIsconnect.BackColor = Color.Green;
                    this.btnConnectAndDIsconnect.ForeColor = Color.White;
                    this.lblConnectedStatus.ForeColor = Color.Gray;
                    this.lblHValue.Text = "00.0";
                    this.lblTValue.Text = "00.0";
                    this.hMeter.SetTHValue = 0;
                    this.tMeter.SetTHValue = 0;
                }
            }
        }

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            // 端口号下拉框
            this.cmbPortName.DataSource = SerialPort.GetPortNames();

            // 波特率下拉框
            string[] baudRateArray = new string[] { "2400", "4800", "9600", "19200", "38400", "57600", "115200" };
            this.cmbBaudRate.DataSource = baudRateArray;
            this.cmbBaudRate.SelectedIndex = 2;

            // 从站地址
            this.nudSlaveId.Value = 1;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.timerReadTHValue.Enabled = false;
        }

        private void btnConnectAndDIsconnect_Click(object sender, EventArgs e)
        {
            if (!IsConnected)
            {
                try
                {
                    //连接设备,这里使用两个参数，其他的用默认的
                    modbusRTU.Connect(this.cmbPortName.Text, Convert.ToInt32(this.cmbBaudRate.Text));
                    IsConnected = true; //标识连接的状态,修改按钮文字
                    this.timerReadTHValue.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示");
                }
            }
            else
            {
                modbusRTU.DisConnect();
                IsConnected = false;
                this.timerReadTHValue.Enabled= false;
            }
        }

        private void timerReadTHValue_Tick(object sender, EventArgs e)
        {
            //读取数据 （2个寄存器，起始地址是：0000H）
            byte[] result = modbusRTU.ReadHoldingRegister(Convert.ToByte(this.nudSlaveId.Value), 0, 2);

            //解析并显示数据
            if (result != null && result.Length == 4)
            {
                int humidity = result[0] * 256 + result[1];//湿度（前面两个）
                int temperature = result[2] * 256 + result[3];//温度

                //显示数字
                this.lblHValue.Text = (humidity * 0.1).ToString();
                this.lblTValue.Text = (temperature * 0.1).ToString();

                //显示图形
                this.hMeter.SetTHValue = humidity * 0.1;
                this.tMeter.SetTHValue = temperature * 0.1;
            }
        }
    }
}
